package fr.inserm.um915.jimpute.model;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.sleepycat.je.Transaction;

public class ModelBuilder
	{
	private static final Logger LOG=Logger.getLogger("fr.inserm.um915.jimpute");

	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
		{
		File imputeDir=null;
		File mergeArchFile=null;
		File dbHome=null;
		int optind=0;
		List<String> loadDbSnp=new ArrayList<String>();
		while(optind<args.length)
				{
				if(args[optind].equals("-h"))
					{
					return;
					}
				else if(args[optind].equals("-d"))
					{
					dbHome=new File(args[++optind]);
					}
				else if(args[optind].equals("-i"))
					{
					imputeDir=new File(args[++optind]);
					if(!imputeDir.exists() || !imputeDir.isDirectory())
						{
						System.err.println(args[optind]+" not an existing directory.");
						return;
						}
					}
				else if(args[optind].equals("-m"))
					{
					mergeArchFile=new File(args[++optind]);
					if(!mergeArchFile.exists() || !mergeArchFile.getName().endsWith(".gz"))
						{
						System.err.println(args[optind]+" not an existing file ending with gz.");
						return;
						}
					}
				else if(args[optind].equals("-s"))
					{
					loadDbSnp.add(args[++optind]);
					loadDbSnp.add(args[++optind]);
					}
				else if(args[optind].equals("--proxy"))
					{
					String proxy=args[++optind];
					int i=proxy.lastIndexOf(':');
					
					System.setProperty("http.proxyHost", proxy.substring(0,i));
					System.setProperty("http.proxyPort", proxy.substring(i+1));
					LOG.info("proxy "+System.getProperty("http.proxyHost")+" "+System.getProperty("http.proxyPort"));
					}
				else if(args[optind].equals("--"))
					{
					optind++;
					break;
					}
				else if(args[optind].startsWith("-"))
					{
					System.err.println("Unnown option: "+args[optind]);
					return;
					}
				else
					{
					break;
					}
				++optind;
				}
		if(mergeArchFile==null)
			{
			System.err.println("Undefined mergeArgchFile");
			return ;
			}
		if(imputeDir==null)
			{
			System.err.println("Undefined impute directory");
			return ;
			}
		if(dbHome==null)
			{
			System.err.println("Undefined dbHome");
			return ;
			}
		if(optind!=args.length)
			{
			System.err.println("Illegal number of arguments");
			return ;
			}
		Transaction txn=null;
		ModelFactory factory=ModelFactory.newInstance();
		factory.setReadOnly(false);
		factory.setDbHome(dbHome);
		Model model=factory.open();
		
		for(int i=0;i+1 < loadDbSnp.size();i+=2)
			{
			Build build=Build.valueOf(loadDbSnp.get(i));
			String url=loadDbSnp.get(i+1);
			model.loadDbSnp(txn, build, url);
			}
		model.loadImputeFolder(txn, imputeDir);
		model.loadRsMerge(txn, mergeArchFile);
		model.close();
		LOG.info("Done.");
		}

}
